#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
劳动赔偿计算器用户界面

功能：
- 提供友好的图形用户界面
- 支持多种赔偿类型的交互式计算
- 实时显示计算结果和详细说明
- 支持结果导出和保存
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
from datetime import datetime
from 劳动赔偿计算器 import LaborCompensationCalculator

class LaborCompensationGUI:
    """劳动赔偿计算器图形界面"""
    
    def __init__(self, root):
        self.root = root
        self.calculator = LaborCompensationCalculator()
        self.results = []
        
        self.setup_ui()
        
    def setup_ui(self):
        """设置用户界面"""
        self.root.title("劳动赔偿计算器 v1.0")
        self.root.geometry("1000x700")
        self.root.resizable(True, True)
        
        # 设置法律主题配色
        self.root.configure(bg='#1e3a5f')  # 深蓝色背景
        
        # 配置ttk样式
        style = ttk.Style()
        style.theme_use('clam')
        
        # 自定义样式配色 - 使用现有的样式名称
        style.configure('TFrame', background='#2c5282', relief='flat')
        style.configure('TLabelFrame', background='#2c5282', foreground='white', 
                       fieldbackground='#3182ce', borderwidth=2)
        style.configure('TLabel', background='#2c5282', foreground='white')
        style.configure('TButton', background='#3182ce', foreground='white',
                       focuscolor='none', borderwidth=1)
        style.map('TButton', background=[('active', '#2b6cb0')])
        style.configure('TCombobox', fieldbackground='white', background='#3182ce')
        style.configure('TEntry', fieldbackground='white')
        
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="劳动赔偿计算器", 
                               font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
        
        # 左侧输入区域
        self.create_input_area(main_frame)
        
        # 右侧结果显示区域
        self.create_result_area(main_frame)
        
        # 底部按钮区域
        self.create_button_area(main_frame)
        
    def create_input_area(self, parent):
        """创建输入区域"""
        input_frame = ttk.LabelFrame(parent, text="计算参数", padding="10")
        input_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=(0, 10))
        
        # 赔偿类型选择
        ttk.Label(input_frame, text="赔偿类型：").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.compensation_type = ttk.Combobox(input_frame, width=25, state="readonly")
        self.compensation_type['values'] = (
            "经济补偿金（N）",
            "赔偿金（2N）",
            "双倍工资",
            "拖欠工资赔偿",
            "工伤医疗赔偿",
            "试用期违法延长赔偿",
            "未休年假工资",
            "生育津贴/产假工资差额",
            "加班费",
            "违法调岗降薪赔偿"
        )
        self.compensation_type.grid(row=0, column=1, sticky=(tk.W, tk.E), pady=5)
        self.compensation_type.bind('<<ComboboxSelected>>', self.on_type_change)
        
        # 城市选择
        ttk.Label(input_frame, text="所在城市：").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.city = ttk.Combobox(input_frame, width=25, state="readonly")
        self.city['values'] = tuple(self.calculator.get_city_list())
        self.city.set("全国通用")
        self.city.grid(row=1, column=1, sticky=(tk.W, tk.E), pady=5)
        
        # 动态输入字段容器
        self.input_fields_frame = ttk.Frame(input_frame)
        self.input_fields_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
        
        # 存储输入控件的字典
        self.input_vars = {}
        
        # 配置列权重
        input_frame.columnconfigure(1, weight=1)
        
    def create_result_area(self, parent):
        """创建结果显示区域"""
        result_frame = ttk.LabelFrame(parent, text="计算结果", padding="10")
        result_frame.grid(row=1, column=1, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 结果显示文本框
        self.result_text = tk.Text(result_frame, wrap=tk.WORD, font=("Consolas", 10),
                                  bg='#f7fafc', fg='#2d3748', insertbackground='#2d3748')
        scrollbar = ttk.Scrollbar(result_frame, orient="vertical", command=self.result_text.yview)
        self.result_text.configure(yscrollcommand=scrollbar.set)
        
        self.result_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 配置网格权重
        result_frame.columnconfigure(0, weight=1)
        result_frame.rowconfigure(0, weight=1)
        
    def create_button_area(self, parent):
        """创建按钮区域"""
        button_frame = ttk.Frame(parent)
        button_frame.grid(row=3, column=0, columnspan=3, pady=20)
        
        # 计算按钮
        calc_button = ttk.Button(button_frame, text="计算", command=self.calculate)
        calc_button.grid(row=0, column=0, padx=5)
        
        # 清空按钮
        clear_button = ttk.Button(button_frame, text="清空", command=self.clear_results)
        clear_button.grid(row=0, column=1, padx=5)
        
        # 保存按钮
        save_button = ttk.Button(button_frame, text="保存结果", command=self.save_results)
        save_button.grid(row=0, column=2, padx=5)
        
        # 城市信息按钮
        city_info_button = ttk.Button(button_frame, text="城市信息", command=self.show_city_info)
        city_info_button.grid(row=0, column=3, padx=5)
        
    def on_type_change(self, event=None):
        """赔偿类型改变时的处理"""
        # 清空之前的输入字段
        for widget in self.input_fields_frame.winfo_children():
            widget.destroy()
        self.input_vars.clear()
        
        compensation_type = self.compensation_type.get()
        
        if compensation_type in ["经济补偿金（N）", "赔偿金（2N）"]:
            self.create_economic_compensation_fields()
        elif compensation_type == "双倍工资":
            self.create_double_salary_fields()
        elif compensation_type == "拖欠工资赔偿":
            self.create_overdue_salary_fields()
        elif compensation_type == "工伤医疗赔偿":
            self.create_work_injury_fields()
        elif compensation_type == "试用期违法延长赔偿":
            self.create_probation_extension_fields()
        elif compensation_type == "未休年假工资":
            self.create_annual_leave_fields()
        elif compensation_type == "生育津贴/产假工资差额":
            self.create_maternity_allowance_fields()
        elif compensation_type == "加班费":
            self.create_overtime_fields()
        elif compensation_type == "违法调岗降薪赔偿":
            self.create_illegal_transfer_fields()
    
    def create_input_field(self, parent, label_text, var_name, row, default_value=""):
        """创建输入字段的通用方法"""
        ttk.Label(parent, text=label_text).grid(row=row, column=0, sticky=tk.W, pady=2)
        var = tk.StringVar(value=default_value)
        entry = ttk.Entry(parent, textvariable=var, width=20)
        entry.grid(row=row, column=1, sticky=(tk.W, tk.E), pady=2, padx=(10, 0))
        self.input_vars[var_name] = var
        return var, entry
    
    def create_economic_compensation_fields(self):
        """创建经济补偿金输入字段"""
        self.create_input_field(self.input_fields_frame, "月平均工资（元）：", "monthly_salary", 0)
        self.create_input_field(self.input_fields_frame, "工作年限（年）：", "work_years", 1)
        
    def create_double_salary_fields(self):
        """创建双倍工资输入字段"""
        self.create_input_field(self.input_fields_frame, "月工资（元）：", "monthly_salary", 0)
        self.create_input_field(self.input_fields_frame, "未签合同月数：", "unsigned_months", 1)
        
    def create_overdue_salary_fields(self):
        """创建拖欠工资输入字段"""
        self.create_input_field(self.input_fields_frame, "拖欠工资金额（元）：", "overdue_amount", 0)
        
    def create_work_injury_fields(self):
        """创建工伤赔偿输入字段"""
        self.create_input_field(self.input_fields_frame, "医疗费用（元）：", "medical_expenses", 0)
        self.create_input_field(self.input_fields_frame, "伤残等级（1-10级）：", "disability_level", 1)
        self.create_input_field(self.input_fields_frame, "月平均工资（元）：", "monthly_salary", 2)
        
    def create_probation_extension_fields(self):
        """创建试用期延长赔偿输入字段"""
        self.create_input_field(self.input_fields_frame, "试用期工资（元）：", "probation_salary", 0)
        self.create_input_field(self.input_fields_frame, "转正工资（元）：", "regular_salary", 1)
        self.create_input_field(self.input_fields_frame, "超期天数：", "excess_days", 2)
        
    def create_annual_leave_fields(self):
        """创建年假工资输入字段"""
        self.create_input_field(self.input_fields_frame, "月平均工资（元）：", "monthly_salary", 0)
        self.create_input_field(self.input_fields_frame, "未休年假天数：", "unused_days", 1)
        
    def create_maternity_allowance_fields(self):
        """创建生育津贴输入字段"""
        self.create_input_field(self.input_fields_frame, "月平均工资（元）：", "monthly_salary", 0)
        self.create_input_field(self.input_fields_frame, "生育津贴（元）：", "maternity_allowance", 1)
        self.create_input_field(self.input_fields_frame, "产假月数：", "maternity_months", 2)
        
    def create_overtime_fields(self):
        """创建加班费输入字段"""
        self.create_input_field(self.input_fields_frame, "月平均工资（元）：", "monthly_salary", 0)
        self.create_input_field(self.input_fields_frame, "工作日加班时长：", "weekday_hours", 1, "0")
        self.create_input_field(self.input_fields_frame, "休息日加班时长：", "weekend_hours", 2, "0")
        self.create_input_field(self.input_fields_frame, "法定节假日加班时长：", "holiday_hours", 3, "0")
        
    def create_illegal_transfer_fields(self):
        """创建违法调岗降薪输入字段"""
        self.create_input_field(self.input_fields_frame, "原工资（元）：", "original_salary", 0)
        self.create_input_field(self.input_fields_frame, "调岗后工资（元）：", "new_salary", 1)
        self.create_input_field(self.input_fields_frame, "降薪月数：", "reduction_months", 2)
        self.create_input_field(self.input_fields_frame, "工作年限（年）：", "work_years", 3)
    
    def get_input_values(self):
        """获取输入值"""
        values = {}
        for key, var in self.input_vars.items():
            try:
                value = var.get().strip()
                if value:
                    if key in ['disability_level', 'unsigned_months', 'excess_days', 'unused_days', 'reduction_months']:
                        values[key] = int(value)
                    else:
                        values[key] = float(value)
                else:
                    values[key] = 0
            except ValueError:
                raise ValueError(f"请输入有效的数字：{key}")
        return values
    
    def calculate(self):
        """执行计算"""
        try:
            compensation_type = self.compensation_type.get()
            if not compensation_type:
                messagebox.showerror("错误", "请选择赔偿类型")
                return
            
            values = self.get_input_values()
            city = self.city.get()
            
            result = None
            
            if compensation_type == "经济补偿金（N）":
                result = self.calculator.calculate_economic_compensation(
                    values['monthly_salary'], values['work_years'], city
                )
            elif compensation_type == "赔偿金（2N）":
                result = self.calculator.calculate_severance_pay(
                    values['monthly_salary'], values['work_years'], city
                )
            elif compensation_type == "双倍工资":
                result = self.calculator.calculate_double_salary(
                    values['monthly_salary'], values['unsigned_months']
                )
            elif compensation_type == "拖欠工资赔偿":
                result = self.calculator.calculate_overdue_salary_compensation(
                    values['overdue_amount']
                )
            elif compensation_type == "工伤医疗赔偿":
                result = self.calculator.calculate_work_injury_compensation(
                    values['medical_expenses'], values['disability_level'], values['monthly_salary']
                )
            elif compensation_type == "试用期违法延长赔偿":
                result = self.calculator.calculate_probation_extension_compensation(
                    values['probation_salary'], values['regular_salary'], values['excess_days']
                )
            elif compensation_type == "未休年假工资":
                result = self.calculator.calculate_annual_leave_compensation(
                    values['monthly_salary'], values['unused_days']
                )
            elif compensation_type == "生育津贴/产假工资差额":
                result = self.calculator.calculate_maternity_allowance_difference(
                    values['monthly_salary'], values['maternity_allowance'], values['maternity_months']
                )
            elif compensation_type == "加班费":
                result = self.calculator.calculate_overtime_compensation(
                    values['monthly_salary'], values.get('weekday_hours', 0),
                    values.get('weekend_hours', 0), values.get('holiday_hours', 0)
                )
            elif compensation_type == "违法调岗降薪赔偿":
                result = self.calculator.calculate_illegal_transfer_compensation(
                    values['original_salary'], values['new_salary'],
                    values['reduction_months'], values['work_years']
                )
            
            if result:
                self.results.append(result)
                self.display_result(result)
                
        except Exception as e:
            messagebox.showerror("计算错误", str(e))
    
    def display_result(self, result):
        """显示计算结果"""
        self.result_text.insert(tk.END, "\n" + "="*60 + "\n")
        self.result_text.insert(tk.END, f"计算时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        self.result_text.insert(tk.END, f"赔偿类型：{result['type']}\n")
        self.result_text.insert(tk.END, f"计算结果：{result['amount']:,.2f}元\n")
        self.result_text.insert(tk.END, f"计算公式：{result['formula']}\n")
        self.result_text.insert(tk.END, f"法律依据：{result['legal_basis']}\n")
        
        if result.get('notes'):
            self.result_text.insert(tk.END, "说明：\n")
            for note in result['notes']:
                self.result_text.insert(tk.END, f"  - {note}\n")
        
        self.result_text.insert(tk.END, "\n")
        self.result_text.see(tk.END)
    
    def clear_results(self):
        """清空结果"""
        self.result_text.delete(1.0, tk.END)
        self.results.clear()
    
    def save_results(self):
        """保存结果"""
        if not self.results:
            messagebox.showwarning("警告", "没有计算结果可保存")
            return
        
        filename = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("文本文件", "*.txt"), ("JSON文件", "*.json"), ("所有文件", "*.*")]
        )
        
        if filename:
            try:
                if filename.endswith('.json'):
                    with open(filename, 'w', encoding='utf-8') as f:
                        json.dump(self.results, f, ensure_ascii=False, indent=2)
                else:
                    report = self.calculator.generate_calculation_report(self.results)
                    with open(filename, 'w', encoding='utf-8') as f:
                        f.write(report)
                
                messagebox.showinfo("成功", f"结果已保存到：{filename}")
            except Exception as e:
                messagebox.showerror("保存失败", str(e))
    
    def show_city_info(self):
        """显示城市信息"""
        city = self.city.get()
        city_info = self.calculator.get_city_info(city)
        
        info_window = tk.Toplevel(self.root)
        info_window.title(f"{city} - 城市信息")
        info_window.geometry("500x300")
        
        info_text = tk.Text(info_window, wrap=tk.WORD, font=("Consolas", 10))
        scrollbar = ttk.Scrollbar(info_window, orient="vertical", command=info_text.yview)
        info_text.configure(yscrollcommand=scrollbar.set)
        
        info_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        info_content = f"""
城市：{city}
社会平均工资：{city_info['social_avg_salary']:,.2f}元/月
经济补偿金三倍封顶：{city_info['compensation_cap']:,.2f}元
产假天数：{city_info['maternity_days']}天
计算基数标准：{city_info['calculation_base']}
特殊规定：{city_info['special_rules']}
        """
        
        info_text.insert(tk.END, info_content)
        info_text.config(state=tk.DISABLED)


def main():
    """主函数"""
    root = tk.Tk()
    app = LaborCompensationGUI(root)
    root.mainloop()


if __name__ == "__main__":
    main()